<template>
  <Container class="single-sale full-sub-gift-sale">
    <div slot="header" class="container-header title title-center">满减送促销</div>
    <div class="bg-light mt">
      <div slot="header" class="container-header">
        <SearchSale @onSearchData="onSearchData" />
      </div>
      <Tabs v-model="tab">
        <Button
          v-if="tab === 'tab1'"
          slot="extra"
          class="item"
          type="primary"
          icon="md-add"
          @click="onJoinAdd"
        >批量加入</Button>
        <Button
          v-if="tab === 'tab2'"
          slot="extra"
          class="item"
          type="primary"
          icon="md-add"
          @click="onJoinDelete"
        >批量撤出</Button>
        <TabPane label="选择赠品" name="tab1">
          <choicePrevent ref="choicePrevent" />
        </TabPane>
        <TabPane :label="label1" name="tab2">
          <present ref="prevent" />
        </TabPane>
      </Tabs>
    </div>
    <div slot="footer" class="container-footer bg-white">
      <Button size="large" @click="jumpPrevPage">返回</Button>
      <Button type="primary" size="large" class="ml" :loading="loading" @click="onJoinPrevent">保存</Button>
    </div>
  </Container>
</template>
<script>
import SearchSale from '@/views/sales/common/SearchSale'
import { setSelectList, setCascaderList } from './list/FullSubGiftSaleSelectMethods'
import choicePrevent from './list/ChoicePreventItem'
import present from './list/present.vue'
import { formatDate, getGift } from './list/FullsubGiftListMethods'
import { getPuduct, isPriceEmpty, onSet } from '@/views/sales/common/TableSaleMethods'
export default {
  components: {
    choicePrevent,
    present,
    SearchSale
  },
  data () {
    return {
      id: this.$route.query.id || '',
      type: this.$route.query.type || '',
      tab: 'tab1',
      loading: false,
      searchForm: {
        brandId: [],
        categoryId: '',
        keyword: '',
        code: '',
        skuCode: ''
      },
      gradeList: [],
      brandList: [],
      label1: (h) => {
        return h('div', [
          h('span', '已选赠品'),
          h('Badge', {
            props: {
              count: this.getSaleNum
            }
          })
        ])
      }
    }
  },
  computed: {
    fullsubgiftAdd () {
      if (this.$store.state.fullSubGiftSale.form.addCheck) {
        return this.$store.state.fullSubGiftSale.form.add
      } else {
        return ''
      }
    },
    fullsubgiftReduce () {
      if (this.$store.state.fullSubGiftSale.form.reduceCheck) {
        return this.$store.state.fullSubGiftSale.form.reduce
      } else {
        return ''
      }
    },
    getSaleNum () {
      return this.$store.getters.getFullSubGiftSaleGiftNum
    },
    grade () {
      return this.$store.state.fullSubGiftSale.form.grade.join(',')
    },
    timeList () {
      return [
        {
          startDatetime: formatDate(
            this.$store.state.fullSubGiftSale.form.date[0],
            true
          ),
          endDatetime: formatDate(
            this.$store.state.fullSubGiftSale.form.date[1],
            true
          )
        }
      ]
    },
    promotionMemberScope () {
      return this.$store.state.fullSubGiftSale.form.grade
    },
    productSkuList () {
      return getPuduct(this.$store.state.fullSubGiftSale.GetsaleData, {
        child: 'productSkuList',
        getParam: ['productId', 'id', 'parentcode', 'code']
      })
    },
    giftSkuList () {
      return getGift(this.$store.state.fullSubGiftSale.GetgiftData, {
        child: 'productSkuList',
        getParam: ['productId', 'id', 'quantity', 'returnPrice', 'parentcode', 'code']
      })
    }
  },
  mounted () {
    if (this.id && !this.$store.state.fullSubGiftSale.GetgiftData.length) this.getData()
  },
  methods: {
    getData () {
      this.$ajaxGet(`/activity/activity_gift_sku_list/${this.id}`).then(data => {
        this.$store.state.fullSubGiftSale.GetgiftData = (data[0] || []).map(item => {
          return {
            id: item.item[0].productId,
            checked: false,
            buttonChecked: false,
            showChildren: false,
            sale: '',
            limitQuantity: '',
            code: item.productSn,
            salePrice: '',
            reduce: '',
            stock: '',
            isShelf: item.isShelf,
            discount: '',
            title: item.title,
            quantity: item.quantity,
            productSkuList: item.item.map(todo => {
              return {
                id: todo.skuId,
                productId: todo.productId,
                productSn: todo.productSn,
                parentcode: item.productSn,
                checked: false,
                buttonChecked: false,
                showChildren: false,
                limitQuantity: '',
                code: todo.skuSn,
                salePrice: todo.productSkuInfo.salePrice,
                reduce: '',
                sale: todo.promotionPrice,
                isShelf: todo.isShelf,
                discount: '',
                title: '',
                stock: todo.productSkuInfo.stock,
                returnPrice: todo.returnPrice,
                quantity: item.quantity
              }
            })
          }
        })
        this.setItem(this.$store.state.fullSubGiftSale.GetgiftData, ['returnPrice'])
        this.onSearchData()
      })
    },
    setItem (data, num) {
      for (let item of data) {
        for (let todo of item.productSkuList) {
          for (let type of num) {
            onSet(todo, item, type)
          }
        }
      }
    },
    onSearchData (param) {
      this.$refs.choicePrevent.getProductData(param)
    },
    onJoinPrevent () {
      let self = this
      if (isPriceEmpty(this.$store.state.fullSubGiftSale.GetgiftData, { index: 'returnPrice', index1: 'checked', childName: 'productSkuList' })) {
        this.$Message.error('退货价不能为空')
        return false
      }
      self.loading = true
      let url = '/activity/full_cut_gift/save'
      if (this.id && this.type) url = '/activity/full_cut_gift/modify'
      let param = {
        activityFullCutGiftDTO: {
          giftProductSkuList: this.giftSkuList,
          addBuyAmount: this.fullsubgiftAdd, //加价购价格
          discountCondition: this.$store.state.fullSubGiftSale.form.con, //优惠条件
          discountCutAmount: this.fullsubgiftReduce, //优惠减多少钱
          isGiftProduct: this.$store.state.fullSubGiftSale.form.giftCheck, //是否赠品
          isParcel: this.$store.state.fullSubGiftSale.form.isParcel
        },
        activityInfoDTO: {
          activityDescription: this.$store.state.fullSubGiftSale.form.remark, //活动备注
          activityName: this.$store.state.fullSubGiftSale.form.name, //活动名称
          endDate: this.timeList[0].endDatetime,
          startDate: this.timeList[0].startDatetime,
          joinTypeEnum: 'PART',
          storeTypeEnumList: this.promotionMemberScope,
          productSkuList: this.productSkuList,
          shelfStatusEnum: 'ON'
        }
      }
      if (this.id && this.type) param.activityFullCutGiftDTO.activityId = this.id
      this.$jsonPost(url, param).then(data => {
        self.$Message.success((this.id && this.type) ? '编辑活动成功' : '新增活动成功')
        self.$store.commit('setFullSubGiftSaleGiftEmpty')
        self.$router.push({ name: 'sales/list' })
        self.loading = false
      }).catch(data => {
        self.loading = false
      })
    },
    jumpPage () {
      this.$router.push({
        name: 'sales/fullSubGift/preview'
      })
    },
    getBlandList () {
      let self = this
      this.$ajaxGet('/promotion/activity/brand/list').then(data => {
        self.brandList = setSelectList(data, { label: 'name', value: 'id' })
      })
    },
    categoryId () {
      let self = this
      this.$ajaxGet('/promotion/activity/category/list').then(data => {
        setCascaderList(data, {
          label: 'name',
          value: 'id',
          child: 'childCategoryList',
          mt: 'categoryDTO'
        })
        self.gradeList = data
      })
    },
    onJoinAdd () {
      this.$refs.choicePrevent.getSaleData('checked')
    },
    jumpPrevPage () {
      this.$router.back()
    },
    onJoinDelete () {
      this.$refs.prevent.deleteSaleData()
    }
  }
}
</script>

